package com.yilin.tms.data.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.yilin.commons.util.StringUtil;
import com.yilin.tms.core.commons.utils.ParamUtil;
import com.yilin.tms.core.entity.data.document.Document;
import com.yilin.tms.core.entity.data.document.DocumentResource;
import com.yilin.tms.core.entity.user.account.Account;
import com.yilin.tms.data.mapper.DocumentResourceMapper;
import com.yilin.tms.data.service.IDocumentResourceService;
import com.yilin.tms.data.service.IDocumentService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;

/**
 * 文档资源服务
 *
 * @author zhangjinyuan
 * @date 2023/08/07  11:11
 */
@Service
public class DocumentResourceService extends ServiceImpl<DocumentResourceMapper, DocumentResource> implements IDocumentResourceService {

    @Resource
    private IDocumentService documentService;

    /**
     * 添加帮助文档资源
     */
    @Override
    @Transactional
    public void addDocumentResource(Account loginUser, DocumentResource resource) {
        Document document = documentService.getById(resource.getDocumentId());
        if (!document.getType()) {
            throw new RuntimeException("该目录不能添加资源");
        }
        if (StringUtil.isNotEmpty(document.getResourceId())) {
            throw new RuntimeException("该目录已添加资源");
        }
        resource.setAddUserId(loginUser.getAddUserId());
        resource.setCreateTime(new Date());
        save(resource);
        document.setResourceId(resource.getId());
        document.setUpdateUserId(loginUser.getId());
        document.setUpdateTime(new Date());
        documentService.updateById(document);
    }

    /**
     * 修改帮助文档资源
     */
    @Override
    public void editDocumentResource(Account loginUser, DocumentResource resource) {
        DocumentResource local = getById(resource.getId());
        ParamUtil.isNull(local, "未查询到资源文件");
        ParamUtil.notEquals("资源不能修改所属目录", resource.getDocumentId(), local.getDocumentId());
        local.setResource(resource.getResource());
        local.setUpdateUserId(loginUser.getId());
        local.setUpdateTime(new Date());
        updateById(local);
    }

    /**
     * 删除帮助文档资源
     */
    @Override
    @Transactional
    public void deleteDocumentResource(Account loginUser, String resourceId) {
        Document document = documentService.getOne(new QueryWrapper<Document>().eq("resource_id", resourceId));
        if (document != null) {
            document.setResourceId(null);
            document.setUpdateUserId(loginUser.getId());
            document.setUpdateTime(new Date());
            documentService.updateById(document);
        }
        removeById(resourceId);
    }
}
